//
//  UserAcountInfo.swift
//  0730Microblog
//
//  Created by ding on 15/7/31.
//  Copyright © 2015年 ding. All rights reserved.
//

import UIKit


class UserAcountInfo: NSObject, NSCoding {
    
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    /// access_token的生命周期，单位是秒数 - 准确的数据类型是`数值`
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expiresDate: NSDate?
    /// 当前授权用户的UID
    var uid: String?
    /// 友好显示名称
    var name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    /// 字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    // MARK: - 归档和解档
    /// 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    /// 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    /// 归档路径
    static private let encodePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("userAccount.plist")
    /// 保存用户信息
    func saveUserAccountInfo() {
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAcountInfo.encodePath)
        print(UserAcountInfo.encodePath)
    }
    
 /// 判断用户信息（access_token、uid、过期时间等）是否存在本地 是就代表用户登陆
    class var isUserAccountInfoStoredLocal: Bool {
        
        return UserAcountInfo.loadSharedUserAccountInfo() != nil
    }
    
    // userAccountInfo 使用频率很高 在整个程序中只会创建一次，优化性能 
    static var userAccountInfo : UserAcountInfo?
    /// 加载用户信息(access_token、uid、过期时间，就是self)
    class func loadSharedUserAccountInfo() -> UserAcountInfo? {
        if userAccountInfo == nil {
            userAccountInfo = NSKeyedUnarchiver.unarchiveObjectWithFile(encodePath) as? UserAcountInfo
        }
        if let date = userAccountInfo?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            userAccountInfo = nil
        }
        
        return userAccountInfo
    }
     /// 加载微博账户信息  注意返回一个加载结果，有没有出错啊
    func loadMicroBlogUserInfo(finished: (loadMicroBlogUserInfoError: NSError?) -> ()) {
        DINGNetTool.sharedNetTool.loadUser(uid!) { (result, error) -> () in
            if error != nil {
                finished(loadMicroBlogUserInfoError: error!)
                return
            }
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            self.saveUserAccountInfo()
            
            
            finished(loadMicroBlogUserInfoError: nil)
//iOS攻城狮
        }
    }
    
    /// 对象描述信息
    override var description: String {
        let properties = ["access_token", "expires_in", "uid", "expiresDate", "avatar_large", "name"]
        
        return "\(dictionaryWithValuesForKeys(properties))"
    }
}
